package com.saihai.jiankang;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.saihai.common.utils.http.HttpUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReadImageFromD {
//    public static void convertFile(String sourceFilePath) {
//        File sourceFile = new File(sourceFilePath);
//        String destinationFilePath = sourceFilePath + ".png";
//
//        try {
//            BufferedImage sourceImage = ImageIO.read(sourceFile);
//
//            ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
//            ImageWriteParam param = writer.getDefaultWriteParam();
//
//            ImageOutputStream ios = ImageIO.createImageOutputStream(new FileOutputStream(new File(destinationFilePath)));
//            writer.setOutput(ios);
//            writer.write(null, new javax.imageio.IIOImage(sourceImage, null, null), param);
//
//            ios.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public static void main(String[] args) {
//        String filePath = "D:\\image\\3d59f59e-e633-4fd3-be0f-eaa67801879e";  // 替换为实际的文件路径
//        convertFile(filePath);
//    }

//    public static void main(String[] args) {
//        try {
//            // 连接到 Modbus 服务器
//            Socket socket = new Socket("172.0.10.126", 3233);
//            OutputStream outputStream = socket.getOutputStream();
//            InputStream inputStream = socket.getInputStream();
//
//            // 构造 Modbus 请求报文
//            byte[] frame = new byte[]{0x01, 0x03, 0x00, 0x04, 0x00, 0x01, (byte) 0xC5, (byte) 0xCB};
//            // 从站地址为 1，功能码 3（读取保持寄存器），起始地址为 100，数量为 3
//
//            // 发送请求
//            outputStream.write(frame);
//
//            // 接收响应
//            byte[] buffer = new byte[1024];
//            int bytesRead = inputStream.read(buffer);
//            // 解析响应
//            if (bytesRead > 0) {
//                byte[] response = new byte[bytesRead];
//                System.arraycopy(buffer, 0, response, 0, bytesRead);
//                // 根据 Modbus 协议格式解析响应数据
//                System.out.println("响应数据：" + bytesRead);
//            }
//
//            // 关闭连接
//            socket.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


//    public static void main(String[] args) {
//        try {
//            // 创建 Socket 连接 Modbus 设备
//            Socket socket = new Socket("172.0.10.126", 3233);
//
//            // 构建 Modbus 读取保持寄存器指令
//            byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x00, 0x00, 0x01, (byte) 0x84, (byte) 0x0A};
//
//            // 发送指令
//            OutputStream outputStream = socket.getOutputStream();
//            outputStream.write(modbusCommand);
//            outputStream.flush();
//
//            // 接收返回帧
//            byte[] buffer = new byte[1024];
//            InputStream inputStream = socket.getInputStream();
//            int bytesRead = inputStream.read(buffer);
//            if (bytesRead > 0) {
//                byte[] response = new byte[bytesRead];
//                System.arraycopy(buffer, 0, response, 0, bytesRead);
//
//                // 打印返回帧到控制台
//                System.out.println("从 Modbus 设备接收到的返回帧：");
//                String ID = "";
//
//                for (byte b : response) {
//                     ID = String.format("%02X ", b);
//                    System.out.print(String.format("%02X ", b));
//                }
//            }
//
//            // 关闭连接
//            socket.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }



    /**
     * 获取水质检测氨氮值
     *
     * @return
     */
    public double getSzAmmonia() {
        byte[] modbusCommand = new byte[]{0x01, 0x03, 0x00, 0x01, 0x00, 0x01, (byte) 0xD5, (byte) 0xCA};
        List<String> list = getTcpData(modbusCommand);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        System.out.println(data);
        return data;
    }

    /**
     * 获取水质检测 温度
     *
     * @return
     */
    public double getSzTemperature() {
        byte[] modbusCommand = new byte[]{0x01, 0x03, 0x00, 0x04, 0x00, 0x01, (byte) 0xC5, (byte) 0xCB};
        List<String> list = getTcpData(modbusCommand);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        System.out.println(data);
        return data;
    }





    /*********************************百叶箱*******************************************************/
    /**
     * 获取百叶箱 温度
     *
     * @return
     */
    public static double getByTemperature() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x00, 0x00, 0x01, (byte) 0x84, (byte) 0x39};

        List<String> list = getTcpData(modbusCommand);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        System.err.println(num);
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 湿度
     *
     * @return
     */
    public static double getByhumidity() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x01, 0x00, 0x01, (byte) 0xD5, (byte) 0xF9};
        List<String> list = getTcpData(modbusCommand);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        System.err.println(num);
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 读气压值
     *
     * @return
     */
    public static double getByAir() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x02, 0x00, 0x01, (byte) 0x25, (byte) 0xF9};
        List<String> list = getTcpData(modbusCommand);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 光照值
     *
     * @return
     */
    public static double getByLight() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x03, 0x00, 0x02, (byte) 0x34, (byte) 0x38};
        List<String> list = getTcpData(modbusCommand);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
//        int num1 = Integer.parseInt(list.get(3).trim(), 16);
//        num1 =num1*16777216;
//
//        int num2 = Integer.parseInt(list.get(4).trim(), 16);
//        num2 =num2*65536;
//
//        int num3 = Integer.parseInt(list.get(5).trim(), 16);
//        num3 =num3*256;
//
//        int num4 = Integer.parseInt(list.get(6).trim(), 16);
//        double data = ((double)num1 + (double)num2 + (double)num3+(double)num4)/10;
        double data = (double)num / 10;
        System.out.println(data);
        return data;
    }


    /**
     * 获取百叶箱检测 PM2.5
     *
     * @return
     */
    public static double getByPm25() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x05, 0x00, 0x01, (byte) 0x94, (byte) 0x38};
        List<String> list = getTcpData(modbusCommand);
//        int num1 = Integer.parseInt(list.get(3).trim(), 16);
//        num1 =num1*256;
//        int num2 = Integer.parseInt(list.get(4).trim(), 16);
//        double data = (double)num1 +num2;
//        System.out.println(data);

        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        return data;
    }

    /**
     * 获取百叶箱检测 PM10
     *
     * @return
     */
    public static double getByPm10() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x06, 0x00, 0x01, (byte) 0x64, (byte) 0x38};
        List<String> list = getTcpData(modbusCommand);
//        int num1 = Integer.parseInt(list.get(3).trim(), 16);
//        num1 =num1*256;
//        int num2 = Integer.parseInt(list.get(4).trim(), 16);
//        double data = (double)num1 +num2;
//        System.out.println(data);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        return data;
    }

    /**
     * 获取百叶箱检测 读取噪音值
     *
     * @return
     */
    public static double getByNoise() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, 0x07, 0x00, 0x01, (byte) 0x35, (byte) 0xF8};
        List<String> list = getTcpData(modbusCommand);
        int num = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double data = (double)num / 10;
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 读 CO2
     *
     * @return
     */
    public static double getByCo2() {
        byte[] modbusCommand = new byte[]{0x01, 0x03, 0x00, 0x08, 0x00, 0x01, (byte) 0x05, (byte) 0xC8};
        List<String> list = getTcpData(modbusCommand);
        int num1 = Integer.parseInt(list.get(3).trim(), 16);
        num1 = num1 *256;
        int num2 = Integer.parseInt(list.get(4).trim(), 16);

        double data = (double)num1 + (double)num2;
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 读 TSP
     *
     * @return
     */
    public static double getByTSP() {
        byte[] modbusCommand = new byte[]{0x01, 0x03, 0x00, 0x09, 0x00, 0x01, (byte) 0x54, (byte) 0x08};
        List<String> list = getTcpData(modbusCommand);
        int num1 = Integer.parseInt(list.get(3).trim(), 16);
        num1 = num1 *256;
        int num2 = Integer.parseInt(list.get(4).trim(), 16);

        double data = (double)num1 + (double)num2;
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 读 风速值
     *
     * @return
     */
    public static double getByWindSpeed() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, (byte) 0x0A, 0x00, 0x01, (byte) 0xA4, (byte) 0x08};
        List<String> list = getTcpData(modbusCommand);
        int num1 = Integer.parseInt(list.get(3).trim(), 16);
        num1 = num1 *256;
        int num2 = Integer.parseInt(list.get(4).trim(), 16);

        double data = (double)num1 + (double)num2;
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 读 风向值
     *
     * @return
     */
    public static double getByWindDirection() {
        byte[] modbusCommand = new byte[]{0x01, 0x03, 0x00, (byte) 0x0B, 0x00, 0x01, (byte) 0xF5, (byte) 0xC8};
        List<String> list = getTcpData(modbusCommand);
        int num1 = Integer.parseInt(list.get(3).trim(), 16);
        num1 = num1 *256;
        int num2 = Integer.parseInt(list.get(4).trim(), 16);

        double data = (double)num1 + (double)num2;
        System.out.println(data);
        return data;
    }

    /**
     * 获取百叶箱检测 读 风级值
     *
     * @return
     */
    public static double getByWindScale() {
        byte[] modbusCommand = new byte[]{0x02, 0x03, 0x00, (byte) 0x0C, 0x00, 0x01, (byte) 0x44, (byte) 0x3A};
        List<String> list = getTcpData(modbusCommand);
        int num1 = Integer.parseInt(list.get(3).trim(), 16);
        num1 = num1 *256;
        int num2 = Integer.parseInt(list.get(4).trim(), 16);

        double data = (double)num1 + (double)num2;
        System.out.println(data);
        return data;
    }

    public static void main(String[] args) {
        getByPm10();
    }


    /**
     * 获取百叶箱检测 读 风级值
     *
     * @return
     */
    public static Map<String,Double> getws() {
        Map<String,Double> map = new HashMap<>();
        byte[] modbusCommand = new byte[]{0x01, 0x03, 0x00, 0x00, 0x00, 0x0A,(byte) 0xC5, (byte) 0xCD};
        List<String> list = getTcpData(modbusCommand);
        int phNum = Integer.parseInt(list.get(3).trim() + list.get(4).trim(), 16);
        double PH = (double)phNum/10;
        int ppmNum = Integer.parseInt(list.get(5).trim() + list.get(6).trim(), 16);
        double ppm = (double)ppmNum/10;

        int codNum = Integer.parseInt(list.get(7).trim() + list.get(8).trim(), 16);
        double cod = (double)codNum/10;

        int wdNum = Integer.parseInt(list.get(11).trim() + list.get(12).trim(), 16);
        double wd = (double)wdNum/10;
        map.put("PH",PH);
        map.put("ppm",ppm);
        map.put("cod",cod);
        map.put("wd",wd);
        System.err.println(PH);
        System.err.println(ppm);
        System.err.println(cod);
        System.err.println(wd);
        return map;
    }





    /**
     * 获取Tcp数据
     *
     * @return
     */
    public static List<String> getTcpData(byte[] bytes) {
        List<String> list = new ArrayList<>();
        try {
            // 创建 Socket 连接 Modbus 设备
            Socket socket = new Socket("172.0.10.126", 3233);

            // 构建 Modbus 读取保持寄存器指令
//            byte[] modbusCommand = new byte[]{0x01, 0x03, 0x00, 0x04, 0x00, 0x01, (byte) 0xC5, (byte) 0xCB};
            byte[] modbusCommand = bytes;


            // 发送指令
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(modbusCommand);
            outputStream.flush();

            // 接收返回帧
            byte[] buffer = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            int bytesRead = inputStream.read(buffer);
            if (bytesRead > 0) {
                byte[] response = new byte[bytesRead];
                System.arraycopy(buffer, 0, response, 0, bytesRead);

                // 打印返回帧到控制台
                System.out.println("从 Modbus 设备接收到的返回帧：");
                String ID = "";

                for (byte b : response) {
                    ID = String.format("%02X ", b);
                    list.add(ID);
                    System.out.print(String.format("%02X ", b));
                }
            }

            // 关闭连接
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }


//    public static void main(String[] args) {
//        try {
//            // 设置串口参数
//            SerialParameters serialParameters = new SerialParameters();
//            serialParameters.setDevice("COMx"); // 根据实际情况设置串口名称
//            serialParameters.setBaudRate(9600);
//            serialParameters.setDataBits(8);
//            serialParameters.setParity(SerialPort.PARITY_NONE);
//            serialParameters.setStopBits(1);
//
//            // 创建串口工厂并使用它创建 Modbus 主站
//            SerialPortFactoryJSSC serialPortFactory = new SerialPortFactoryJSSC();
//            ModbusMaster master = ModbusMasterFactory.createModbusMasterRTU(serialPortFactory, serialParameters);
//
//            // 连接到 Modbus 设备
//            master.connect();
//
//            // 发送 ASCII 码 "AT"
//            byte[] atCommand = {'A', 'T'};
//            master.writeMultipleRegisters(1, 0, atCommand.length, atCommand);
//
//            // 读取响应
//            int[] responseRegisters = master.readHoldingRegisters(1, 0, atCommand.length);
//            byte[] responseBytes = new byte[responseRegisters.length];
//            for (int i = 0; i < responseRegisters.length; i++) {
//                responseBytes[i] = (byte) responseRegisters[i];
//            }
//
//            // 输出响应
//            System.out.println("Response: " + new String(responseBytes));
//
//            // 断开连接
//            master.disconnect();
//        } catch (ModbusIOException | ModbusNumberException | ModbusProtocolException e) {
//            e.printStackTrace();
//        }
//    }


}
